package com.gaobo.demo.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @author masc
 * @date 2022-08-29 10:49
 * <p></p>
 */
@RestController
public class OutputWolrd {

    /**
     * 获取报告
     */
    @RequestMapping("/download/word/test")
    public void downloadWord(HttpServletResponse response) throws Exception {
        ClassPathResource resource = new ClassPathResource("template.docx");
        InputStream inputStream = resource.getInputStream();
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(
                new HashMap<String, Object>() {{
                    put("ID", "ZHANG_SAN_091");
                    put("NO", "KB.6890451");
                    put("taitou", "深圳XX家装有限公司");
                    put("consignee", "丙丁");
                }});
        // 文件流传输
//        template.writeAndClose(new FileOutputStream("output.docx"));
        // 使用网络流进行传输
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("付款通知书.docx", "UTF-8"));

// HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }
}
